package com.xysd.express.activity;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.xysd.express.R;
import com.xysd.express.base.BaseActivity;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;

@ContentView(R.layout.activity_voice)
public class VoiceActivity extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.hint_tv)
    private TextView hint_tv;
    @ViewInject(R.id.undervoice_tv)
    private TextView undervoice_tv;
    @ViewInject(R.id.voice_img)
    private ImageView voice_img;

    @Override
    protected void init() {
        setTitleBar(getResources().getString(R.string.app_name));
        voice_img.setOnClickListener(this);
        hint_tv.setText("我要找顺丰快递...\n我要送货...\n从平昌到成都...\n我要找跑腿...\n我要代购...");

        voice_img.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        undervoice_tv.setText("语音录入中...");
                        undervoice_tv.setTextColor(getResources().getColor(R.color.orange));
                        playSound("start.mp3");
                        break;
                    case MotionEvent.ACTION_UP:
                        undervoice_tv.setText("按下喊话");
                        undervoice_tv.setTextColor(getResources().getColor(R.color.gray));
                        playSound("end.mp3");
                        break;
                }
                return false;
            }

        });
    }


    private AssetManager assetManager;
    MediaPlayer player;
    /**
     * 播放语音
     *
     * @param path asset文件夹里的文件名
     */
    public void playSound(String path) {
        if (player!=null&&player.isPlaying()){
            player.pause();
            player.release();
        }
        player = new MediaPlayer();
        try {

            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(path);
            player.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();

            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onDestroy() {
        if (player!=null)
        player.release();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.voice_img:

                break;
        }
    }
}
